from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image

#导包 检索
from django.db.models import Q
#随机库
import random

import json
#文件流
import io
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.models import *
import cv2

# 导入序列化类
from myapp.myser import *




# 注册接口
class MdReg(APIView):
    def get(self,request):
        # 获取数据
        username = request.GET.get('username')
        password = request.GET.get('password')

        # 入库操作
        users = MdUser(username=username,password=password)
        # 保存
        users.save()
        return Response({
            'code': 200,
            'message': '注册成功'
        })


# 登录接口
class MdLogin(APIView):
    def get(self,request):
        # 获取数据
        username = request.GET.get('username')
        password = request.GET.get('password')
        # 与数据库数据验证
        users = MdUser.objects.filter(username=username,password=password).first()
        if users:
            return Response({
                'code': 200,
                'message':'登录成功',
                'data': users.id
            })
        else:
            return Response({
                'code': 403,
                'message':'用户名或密码错误'

            })


# 定义文件上传通用类
class UploadTu(APIView):
    def post(self, request):
        # 接收参数
        myfile = request.FILES.get('file')
        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT, '', myfile.name), 'wb')
        # 写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()
        # 设置图片打开路径
        imgpath = './static/upload/' + myfile.name
        # 打开图片
        im = Image.open(UPLOAD_ROOT + '/' + myfile.name)
        # 生成画笔对象
        draw = ImageDraw.Draw(im)
        # 设定添加文字的字体
        font = ImageFont.truetype(font='C:\\Windows\\Fonts\\lucon.ttf', size=30)
        # 绘制图片
        draw.text((50, 200), 'django2.0.4', fill=(76, 234, 124, 180), font=font)
        # 图像压缩
        # 读图
        img = cv2.imread(UPLOAD_ROOT + '/' + myfile.name)
        # 压缩操作
        cv2.imwrite(UPLOAD_ROOT + '/' + myfile.name, img, [cv2.IMWRITE_JPEG_QUALITY, 50])

        # 存储图片
        im.save(UPLOAD_ROOT + '/' + myfile.name)

        return Response({
            'filename': myfile.name
        })


# 导包
import upyun
# 又拍云
class KsYun(APIView):
    def post(self,request):

        # 获取文件
        file = request.FILES.get('file')
        # 新建又拍云实例
        up = upyun.UpYun('1907b','tt1216124438','ahrPZf37Jw6KXBtRxOoF1RrEwKmnapNg')
        # 声明头部信息
        headers = {'x-gmkerl-rotate':'auto'}
        # 上传图片
        for chunk in file.chunks():
            res = up.put('/'+file.name,chunk,checksum=True,headers=headers)

                    #返回结果
            print(file.name)
        return Response({'filename':file.name})




# 移动文件
class YiDongyun(APIView):
    def get(self, request):
        # 接收创建的目录名称
        up = upyun.UpYun('1907b', 'tt1216124438', 'ahrPZf37Jw6KXBtRxOoF1RrEwKmnapNg')
        # 移动文件
        up.move('/jwt.png', '/kaoshi/jwt.png')
        return Response({
            'message': '移动成功',

        })


# 又拍云删除图片
class DeleteYUn(APIView):
    def get(self, request):
        # 接收创建的目录名称
        up = upyun.UpYun('1907b', 'tt1216124438', 'ahrPZf37Jw6KXBtRxOoF1RrEwKmnapNg')

        # 删除文件
        up.delete('/kaoshi/jwt.png')
        return Response({
            'message': '删除成功',

        })



# 展示列表
class Allgoods(APIView):
    def get(self,request):

        # 检索
        text = request.GET.get('text',None)
        #排序字段
        coloum = request.GET.get('coloum',None)
        #排序方法
        sort_order = request.GET.get('order','')
        # 当前页面
        page =request.GET.get('page',1)
        #页面显示多少
        size = request.GET.get('size',2)
        # 开始从哪开始切
        data_start = (int(page)-1) * int(size)
        # 操作切到哪
        data_end = int(page) * int(size)
        # 查询  切片操作
        if coloum:

            good = Goods.objects.all().order_by(sort_order+coloum)[data_start:data_end]
        else:
            good = Goods.objects.all()[data_start:data_end]
        # 判断是否进行模糊查询
        if text:
            good = Goods.objects.filter(Q(name__contains=text) | Q(desc__contains=text))[data_start:data_end]
            count = Goods.objects.filter(Q(name__contains=text) | Q(desc__contains=text)).count()
        else:
            # 查询所有商品个数
            count = Goods.objects.count()

        # 获取商品表数据
        good = Goods.objects.all()[data_start:data_end]
        # 查询总数量
        count = Goods.objects.count()
        # 序列化操作
        goods_ser = GoodsSer(good,many=True)

        return Response({
            'data':goods_ser.data,
            'total': count
        })









